#!/usr/bin/env python3
"""
ES索引迁移工具快速启动脚本
帮助用户快速配置和使用迁移工具
"""

import json
import os
import sys
from es_index_migrator import ESIndexMigrator

def collect_source_config():
    """收集源ES配置信息"""
    print("=== 配置源ES环境 (ES 6.8) ===")
    
    host = input("请输入源ES主机地址 [localhost]: ").strip() or "localhost"
    port = input("请输入源ES端口 [9200]: ").strip() or "9200"
    
    use_auth = input("是否需要认证？(y/n) [n]: ").strip().lower()
    username = None
    password = None
    
    if use_auth == 'y':
        username = input("用户名: ").strip()
        password = input("密码: ").strip()
    
    return {
        'host': host,
        'port': int(port),
        'scheme': 'http',
        'username': username,
        'password': password,
        'verify_certs': False,
        'timeout': 30
    }

def collect_target_config():
    """收集目标ES配置信息"""
    print("\n=== 配置目标ES环境 (ES 7.17.27 带SSL) ===")
    
    host = input("请输入目标ES主机地址 [localhost]: ").strip() or "localhost"
    port = input("请输入目标ES端口 [9200]: ").strip() or "9200"
    
    username = input("请输入X-PACK用户名 [elastic]: ").strip() or "elastic"
    password = input("请输入X-PACK密码: ").strip()
    
    use_ssl = input("是否使用SSL？(y/n) [y]: ").strip().lower()
    scheme = 'https' if use_ssl != 'n' else 'http'
    verify_certs = True if use_ssl != 'n' else False
    
    ca_certs = None
    if verify_certs:
        ca_path = input("CA证书路径 (可选，直接回车跳过): ").strip()
        if ca_path and os.path.exists(ca_path):
            ca_certs = ca_path
        else:
            print("警告: 未提供CA证书，将跳过证书验证")
            verify_certs = False
    
    return {
        'host': host,
        'port': int(port),
        'scheme': scheme,
        'username': username,
        'password': password,
        'verify_certs': verify_certs,
        'ca_certs': ca_certs,
        'ssl_show_warn': False,
        'timeout': 60
    }

def test_connections(source_config, target_config):
    """测试ES连接"""
    print("\n=== 测试连接 ===")
    
    try:
        migrator = ESIndexMigrator(source_config, target_config)
        print("✅ 源ES和目标ES连接成功！")
        return migrator
    except Exception as e:
        print(f"❌ 连接失败: {e}")
        print("请检查配置信息并重试")
        return None

def preview_migration(migrator):
    """预览迁移"""
    print("\n=== 预览迁移 ===")
    
    try:
        # 临时启用预览模式
        from config import MIGRATION_CONFIG
        original_dry_run = MIGRATION_CONFIG.get('dry_run', False)
        MIGRATION_CONFIG['dry_run'] = True
        
        # 导出索引结构
        exported_data = migrator.export_index_structures('preview_indices.json')
        
        if not exported_data:
            print("❌ 源ES中没有找到可迁移的索引")
            return False
        
        print(f"📋 将要迁移的索引 ({len(exported_data)} 个):")
        for index_name in exported_data.keys():
            print(f"  - {index_name}")
        
        # 预览创建过程
        print("\n预览索引创建过程...")
        import_results = migrator.import_index_structures('preview_indices.json')
        
        # 恢复原始设置
        MIGRATION_CONFIG['dry_run'] = original_dry_run
        
        # 清理预览文件
        if os.path.exists('preview_indices.json'):
            os.remove('preview_indices.json')
        
        return True
        
    except Exception as e:
        print(f"❌ 预览过程出错: {e}")
        return False

def confirm_migration():
    """确认迁移"""
    print("\n=== 确认迁移 ===")
    
    warnings = [
        "⚠️  重要提醒:",
        "   1. 此操作只迁移索引结构，不迁移数据",
        "   2. 如果目标ES中存在同名索引，可能会被覆盖",
        "   3. 建议先在测试环境验证",
        "   4. 确保已备份重要数据"
    ]
    
    for warning in warnings:
        print(warning)
    
    confirm = input("\n确认开始迁移？(yes/no): ").strip().lower()
    return confirm == 'yes'

def execute_migration(migrator):
    """执行迁移"""
    print("\n=== 执行迁移 ===")
    
    try:
        results = migrator.migrate_all()
        
        print("\n" + "="*50)
        print("🎉 迁移完成！")
        print(f"📊 统计信息:")
        print(f"   导出索引数量: {results['exported_count']}")
        print(f"   成功创建: {len(results['import_results']['success'])}")
        print(f"   失败: {len(results['import_results']['failed'])}")
        print(f"   跳过: {len(results['import_results']['skipped'])}")
        
        if results['import_results']['failed']:
            print(f"\n❌ 失败的索引:")
            for failed in results['import_results']['failed']:
                print(f"   - {failed['index']}: {failed['error']}")
        
        if results['import_results']['success']:
            print(f"\n✅ 成功创建的索引:")
            for success in results['import_results']['success']:
                print(f"   - {success}")
        
        print("="*50)
        print("📝 详细日志已保存到: es_migration.log")
        
        return True
        
    except Exception as e:
        print(f"❌ 迁移过程中发生错误: {e}")
        print("📝 请查看日志文件 es_migration.log 获取详细信息")
        return False

def main():
    """主函数"""
    print("🚀 ES索引迁移工具快速启动")
    print("=" * 50)
    
    # 步骤1: 收集配置信息
    source_config = collect_source_config()
    target_config = collect_target_config()
    
    # 步骤2: 测试连接
    migrator = test_connections(source_config, target_config)
    if not migrator:
        sys.exit(1)
    
    # 步骤3: 预览迁移
    if not preview_migration(migrator):
        sys.exit(1)
    
    # 步骤4: 确认迁移
    if not confirm_migration():
        print("用户取消迁移")
        sys.exit(0)
    
    # 步骤5: 执行迁移
    success = execute_migration(migrator)
    
    if success:
        print("\n✅ 迁移工具执行完成")
    else:
        print("\n❌ 迁移过程中出现问题")
        sys.exit(1)

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n\n用户中断操作")
        sys.exit(0)
    except Exception as e:
        print(f"\n❌ 程序异常: {e}")
        sys.exit(1) 